package cn.bijy.sqlsession;

import cn.bijy.pojo.Configuration;
import cn.bijy.pojo.MapedStatement;
import cn.bijy.utils.GenericTokenParser;
import cn.bijy.utils.ParameterMapping;
import cn.bijy.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor{
    private Connection connection = null;
    @Override
    public <E> List<E> query(Configuration configuration, MapedStatement mapedStatement, Object... param) throws Exception {
        connection = configuration.getDataSource().getConnection();
        String sql = mapedStatement.getSql();
        Class<?> paramterType = mapedStatement.getParamterType();
        Class<?> resultType = mapedStatement.getResultType();
        BoundSql boundSql = getBoundSql(sql);
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            String content = parameterMapping.getContent();
            Field declaredField = paramterType.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(param[0]);
            preparedStatement.setObject(i+1,o);
        }

        ResultSet resultSet = preparedStatement.executeQuery();
        ArrayList<E> list = new ArrayList<>();
        while (resultSet.next()){
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            E o = (E)resultType.newInstance();
            for (int i = 1; i <= columnCount; i++) {
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);

                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultType);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o,value);
            }
            list.add(o);
        }
        return list;
    }

    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String sqlText = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(sqlText,parameterMappings);
        return boundSql;
    }

    @Override
    public void close() throws SQLException {
        connection.close();
    }

    @Override
    public <T> T save(Configuration configuration, MapedStatement mapedStatement, Object... param) throws SQLException, NoSuchFieldException, IllegalAccessException {
        connection = configuration.getDataSource().getConnection();
        String sql = mapedStatement.getSql();
        Class<?> paramterType = mapedStatement.getParamterType();
        BoundSql boundSql = getBoundSql(sql);
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            String content = parameterMapping.getContent();
            Field declaredField = paramterType.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(param[0]);
            preparedStatement.setObject(i+1,o);
        }
        preparedStatement.execute();
        return null;
    }

    @Override
    public <T> T update(Configuration configuration, MapedStatement mapedStatement, Object... param) throws Exception {
        connection = configuration.getDataSource().getConnection();
        String sql = mapedStatement.getSql();
        Class<?> paramterType = mapedStatement.getParamterType();
        BoundSql boundSql = getBoundSql(sql);
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            String content = parameterMapping.getContent();
            Field declaredField = paramterType.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(param[0]);
            preparedStatement.setObject(i+1,o);
        }
        preparedStatement.executeUpdate();
        return null;
    }
}
